<template>
  <div class="room pad">
    <div class="head">
      <span>存储空间设置</span>
    </div>
    <el-tabs class="m-t-b" type="border-card">
      <el-tab-pane label="存储空间销售列表">
        <el-table stripe border :data="rooms" v-loading="loading">
          <el-table-column label="注册用户编号" prop="userId"></el-table-column>
          <el-table-column label="内存空间">
            <template slot-scope="scope">
              {{scope.row.picNum + '张 + ' + scope.row.picRam + '兆'}}
            </template>
          </el-table-column>
          <el-table-column label="价格">
            <template slot-scope="scope">
              {{scope.row.price + '元'}}
            </template>
          </el-table-column>
          <el-table-column label="购买时间" prop="createDate"></el-table-column>
        </el-table>
        <el-pagination
          class="m-t-b flex"
          :page-size="pageSize"
          layout="prev, pager, next"
          :current-page="curSalePage"
          @current-change="handlePagiSale"
          :total="saleTotal">
        </el-pagination>
      </el-tab-pane>
      <el-tab-pane label="存储空间单价设置">
        <el-button :disabled="prices.length === 6" @click="openAddDialog" type="primary">
          <i class="el-icon-plus"></i> 添加单价
        </el-button>
        <el-alert
          v-if="prices.length === 6"
          style="margin-top: 10px;"
          title="存储空间单价设置允许最多同时存在6条数据"
          type="warning"
          show-icon>
        </el-alert>
        <el-table class="m-t-b" stripe border :data="prices" v-loading="loading1">
          <el-table-column label="关联消息提醒编号" prop="remindNum"></el-table-column>
          <el-table-column label="内存空间">
            <template slot-scope="scope">
              {{scope.row.picNum + '张 + ' + scope.row.picRam + '兆'}}
            </template>
          </el-table-column>
          <el-table-column label="价格">
            <template slot-scope="scope">
              {{scope.row.price + '元'}}
            </template>
          </el-table-column>
          <el-table-column label="创建时间" prop="createDate"></el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button @click="openUpdateDialog(scope.row)" icon="el-icon-edit" circle></el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          class="m-t-b flex"
          :page-size="pageSize"
          layout="prev, pager, next"
          :current-page="curRoomPage"
          @current-change="handlePagi"
          :total="roomTotal">
        </el-pagination>
      </el-tab-pane>
    </el-tabs>
    <el-dialog :title="dialogTitle" :visible.sync="showDialog">
      <el-form :model="price" ref="price" :rules="rules" label-position="top">
        <el-form-item label="关联消息提醒编号" prop="templateId">
          <el-select filterable v-model="price.templateId">
            <el-option v-for="item in templates" :key="item.templateId" :value="item.templateId" :label="item.remindNum"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="内存空间(单位以M(兆)计算)">
          <el-input-number v-model="price.picRam" :precision="0" :min="1" :max="100">
          </el-input-number>
        </el-form-item>
        <el-form-item label="张数">
          <el-input-number v-model="price.picNum" :min="1" :max="100"></el-input-number>
        </el-form-item>
        <el-form-item label="单价" prop="price">
          <el-input-number v-model="price.price" :min="0" :max="100"></el-input-number>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="hideDialog">取 消</el-button>
        <el-button type="primary" @click="handleConfirm('price')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { formatDate, notifySuccess } from '../util'
import {
  getAllServiceMsgTemplate,
  addRoom,
  getRoomList,
  getRoomSaleList,
  updateRoom
} from '../api'

export default {
  name: 'room',
  data () {
    const cheackPrice = (rules, value, callback) => {
      if (value < 0.01) {
        return callback(new Error('价格必须大于0.01元!'))
      };
      callback()
    };
    return {
      dialogTitle: '设置单价',
      loading: true,
      isUpdate: false,
      showDialog: false,
      pageSize: 10,
      curRoomPage: 1,
      roomTotal: 0,
      curSalePage: 1,
      saleTotal: 0,
      templates: [],
      rooms: [],
      prices: [],
      price: {
        templateId: '',
        picRam: '',
        price: '',
        picNum: 1
      },
      rules: {
        templateId: [
          { required: true, message: '该项不能为空!', trigger: 'blur' }
        ],
        price: [
          { validator: cheackPrice, trigger: 'blur' }
        ],
        picRam: [
          { required: true, message: '该项不能为空!', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    hideDialog () {
      this.showDialog = false
    },
    handlePagi (page) {
      this.fetchRoomList(page)
    },
    handlePagiSale (page) {
      this.fetchRoomSaleList(page)
    },
    handleConfirm (form) {
      this.$refs[form].validate(valid => {
        if (valid) {
          if (this.dialogTitle === '修改单价') {
            updateRoom({
              settingId: this.price.settingId,
              templateId: this.price.templateId,
              picRam: this.price.picRam * 1024,
              picNum: this.price.picNum,
              price: this.price.price,
            })
            .then(res => {
              if (res.data.code === 1) {
                notifySuccess(this)
                this.showDialog = false
                this.fetchRoomList(1)
              } else {
                this.$message.error('网络异常!')
              }
            })
            .catch(e => {
              this.$message.error('网络异常!')
            })
          } else {
            addRoom({
              templateId: this.price.templateId,
              picRam: this.price.picRam * 1024,
              picNum: this.price.picNum,
              price: this.price.price,
            })
            .then(res => {
              if (res.data.code === 1) {
                notifySuccess(this)
                this.showDialog = false
                this.fetchRoomList(1)
              } else {
                this.$message.error(res.data.msg || '网络异常!')
              }
            })
            .catch(e => {
              this.$message.error('网络异常!')
            })
          }
        } else {
          return false
        }
      })
    },
    openAddDialog () {
      if (!this.$checkAuth('canAddRoomPrice')) {
        return this.$message.error('暂无对应操作权限!')
      };
      this.dialogTitle = '设置单价'
      this.isUpdate = false
      this.showDialog = true
    },
    openUpdateDialog (data) {
      if (!this.$checkAuth('canEditRoomPrice')) {
        return this.$message.error('暂无对应操作权限!')
      };
      this.dialogTitle = '修改单价'
      this.isUpdate = true
      this.price = data
      this.showDialog = true
    },
    fetchTemplate () { // 获取消息模板
      getAllServiceMsgTemplate()
      .then (res => {
        if (res.data.code === 1) {
          this.templates = res.data.data || []
        } else {
          this.$message.error(res.data.msg || '网络异常!')
        }
      })
      .catch (e => {
        this.$message.error('网络异常!')
      })
    },
    fetchRoomList (index) { // 获取存储空间单价设置列表
      this.loading1 = true
      getRoomList({
        index,
        count: this.pageSize
      })
      .then(res => {
        if (res.data.code === 1) {
          let list = res.data.data.list || []
          for (let i = 0; i < list.length; i ++) {
            list[i].picRam = list[i].picRam / 1024
            list[i].createDate = formatDate(list[i].createDate)
          }
          this.roomTotal = res.data.data.totalRecord
          this.prices = list
        } else {
          this.$message.error(res.data.msg || '网络异常!')
        }
        this.loading1 = false
      })
      .catch(e => {
        this.loading1 = false
        this.$message.error('网络异常!')
      })
    },
    fetchRoomSaleList (index) {
      this.loading = true
      getRoomSaleList({
        index,
        count: this.pageSize
      })
      .then(res => {
        if (res.data.code === 1) {
          let list = res.data.data.list || []
          for (let i = 0; i < list.length; i ++) {
            list[i].createDate = formatDate(list[i].createDate)
            list[i].picRam = Math.floor(list[i].picRam / 1024)
          }
          this.saleTotal = res.data.data.totalRecord
          this.rooms = list
        } else {
          this.$message.error(res.data.msg || '网络异常!')
        }
        this.loading = false
      })
      .catch(e => {
        this.loading = false
        this.$message.error('网络异常!')
      })
    }
  },
  created () {
    this.fetchRoomSaleList(1)
    this.fetchTemplate()
    this.fetchRoomList(1)
  }
}
</script>
<style lang="scss">
  .room {
    .tip {
      color: #ff7675;
      font-size: 20px;
      margin-left: 6px;
    }
    table {
      .cell {
        text-align: center;
      }
    }
  }
</style>
